package com.anji.plus.gaea.log;

import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy;

import com.anji.plus.gaea.annotation.condition.ConditionalOnGaeaComponent;
import com.anji.plus.gaea.log.aspect.GaeaAuditLogAspect;
import com.anji.plus.gaea.log.config.GaeaAuditLogProperties;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.client.RestTemplate;

/**
 * 日志组件
 *
 * @author lr
 * @since 2021-01-15
 */
@Configuration
@EnableConfigurationProperties(GaeaAuditLogProperties.class)
@ConditionalOnGaeaComponent(GaeaAuditLogProperties.COMPONENT_NAME)
public class GaeaLogAutoConfiguration {

    @Value("${gaea.threadPool.corePoolSize:5}")
    private Integer corePoolSize;

    @Value("${gaea.threadPool.maxPoolSize:50}")
    private Integer maxPoolSize;

    @Value("${gaea.threadPool.queueCapacity:100}")
    private Integer queueCapacity;

    @Value("${gaea.threadPool.keepAliveInSeconds:300}")
    private Integer keepAliveInSeconds;

    @Bean
    public GaeaAuditLogAspect auditLogAspect() {
        return new GaeaAuditLogAspect();
    }

    @Bean(name = "logRestTemplate")
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }

    @Bean(name = "threadPoolGaeaLogExecutor")
    @Primary
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor poolTaskExecutor = new ThreadPoolTaskExecutor();
        //线程池维护线程的最少数量
        poolTaskExecutor.setCorePoolSize(corePoolSize);

        //线程池维护线程的最大数量
        poolTaskExecutor.setMaxPoolSize(maxPoolSize);

        //线程池所使用的缓冲队列
        poolTaskExecutor.setQueueCapacity(queueCapacity);

        //线程池维护线程所允许的空闲时间
        poolTaskExecutor.setKeepAliveSeconds(keepAliveInSeconds);
        poolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        poolTaskExecutor.setRejectedExecutionHandler(new CallerRunsPolicy());
        poolTaskExecutor.setThreadGroupName("gaeaThreadGroup");
        poolTaskExecutor.setThreadNamePrefix("gaea");
        return poolTaskExecutor;
    }

}
